﻿Public Class App


    Private Shared ReadOnly lazy As New Lazy(Of App)(Function() New App())

    Private oMessageHandler As New MessageHandler
    Private oPeople As New People

    Public Event SMSAdded(Person As Person, SMS As SMSMessage)
    Public Event ReceiptArrived()
    Public Event NewContact(Contact As Person)
    Private ignorefiles As New Collection

    Public Shared ReadOnly Property Instance() As App
        Get
            Return lazy.Value
        End Get
    End Property

    Public Property Contacts() As People
        Get
            Return oPeople
        End Get
        Set(value As People)
            oPeople = value
            Save()
        End Set
    End Property

    Public Sub AddNewPerson(Person As Person)

        oPeople.Add(Person)
        Save()
        RaiseEvent NewContact(Person)

    End Sub

    Protected Sub New()

        oPeople = XMLHelper.DeserializeObject(oPeople, AppDomain.CurrentDomain.BaseDirectory & "SMS.xml")

    End Sub

    Public Sub Import(Text As String)

        Dim oSMS As SMSMessages = oMessageHandler.ImportMessages(Text)

        'Process the messages and attach to the right people
        Dim s As SMSMessage

        For Each s In oSMS
            AddSMSToPerson(s)
        Next

    End Sub

    Public Sub ProcessIncomingMessage(Text As String)

        'Dim s As String = Mid(Text, 8, 7)
        'Check to see if it's on the ignore list
        Dim startText As String = Left(Text, 20)

        If InStr(startText, "message"":", CompareMethod.Text) > 0 Then
            'Read the SMS message
            Dim mySMS As SMSMessage = oMessageHandler.ReadSMS(Text)
            If ignorefiles.Contains(mySMS.DateTime) = True Then Return

            AddSMSToPerson(mySMS)

        ElseIf InStr(startText, "receipts"":", CompareMethod.Text) > 0 Then
            'Read the receipt
            Dim myRec As SMSReceipt = oMessageHandler.ReadReceipt(Text)

            'Update receipt to TRUE and Update the Date to the Date in the receipt
            'Look through oPeople and see if the ToNumber can be matched up, then look
            'through the SMS messages and see if a message can be found with a suitable DateTime
            'Not sure at this stage if it is the actual time sent or the time of the original message

            Dim p As Person
            For Each p In oPeople
                If p.Telephone = myRec.ToPhone Then
                    Dim s As SMSMessage
                    For Each s In p.SMSMessages
                        If myRec.DateTime = s.DateTime Then
                            s.Receipt = True
                            Exit For
                        End If
                    Next
                End If
            Next

        Else
            'Throw and invalid message exception


        End If

        Save()

    End Sub

    Public Sub SendSMSMessage(SMS As SMSMessage, DropBoxOutBoxPath As String, DropBoxInBoxPath As String)

        Dim SMSText As String = oMessageHandler.CreateMessage(SMS)

        Dim OutFile As String = DropBoxOutBoxPath & "plus" & Utility.StripPhone(SMS.ToPhone) & "_" & Utility.DateToEpoch(SMS.DateTime) & ".json"
        Dim InFile As String = DropBoxInBoxPath & "plus" & Utility.StripPhone(SMS.ToPhone) & "_" & Utility.DateToEpoch(SMS.DateTime) & ".json"

        SendFile(OutFile, SMSText)
        SendFile(InFile, SMSText)

        ignorefiles.Add(SMSText, SMS.DateTime)

        AddSMSToPerson(SMS)
        Save()

    End Sub

    Private Sub SendFile(FilePath As String, SMSText As String)

        If System.IO.File.Exists(FilePath) = False Then
            Dim objWriter As New System.IO.StreamWriter(FilePath)
            objWriter.Write(SMSText)
            objWriter.Close()
        End If

    End Sub


    Private Sub AddSMSToPerson(SMS As SMSMessage)

        Dim found As Boolean = False
        Dim searchNo As String
        Dim searchName As String
        Dim ps As New Person

        If SMS.FromName = "NULL_VALUE" Then
            searchNo = SMS.ToPhone
            searchName = SMS.ToName
            ps.Name = SMS.ToName
            ps.Telephone = SMS.ToPhone
        Else
            searchNo = SMS.FromPhone
            searchName = SMS.FromName
            ps.Name = SMS.FromName
            ps.Telephone = SMS.FromPhone
        End If

        Dim p As Person
        For Each p In oPeople
            If p.Telephone = searchNo Or p.Name = searchName Then
                'Add the SMS to this person
                p.SMSMessages.Add(SMS)
                found = True

                'Raise the event
                RaiseEvent SMSAdded(p, SMS)
                Exit For
            End If
        Next

        If found = False Then
            AddNewPerson(ps)
            ps.SMSMessages.Add(SMS)
        End If

        'Save the collection to file
        'Save()

    End Sub

    Public Sub Save()

        XMLHelper.SerializeObject(oPeople, AppDomain.CurrentDomain.BaseDirectory & "SMS.xml")

    End Sub

End Class
